package com.imooc.concurrent.memoryVisibility;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 为什么不能保证原子性,number++其实分三步执行
 */
public class VolatileDemo1 {
	private volatile int number = 0;
	public int getNumber(){
		return this.number;
	}

	public void increase(){
		try {
			//睡眠一会，让效果更明显
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.number++;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final VolatileDemo1 volDemo = new VolatileDemo1();
		for(int i = 0 ; i < 500 ; i++){
			new Thread(()->volDemo.increase()).start();
		}

		//如果还有子线程在运行，主线程就让出CPU资源，
		//直到所有的子线程都运行完了，主线程再继续往下执行
		while(Thread.activeCount() > 1){
			Thread.yield();
		}

		System.out.println("number : " + volDemo.getNumber());
	}

}
